package com.cg.controller;

import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import reactor.core.publisher.Flux;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;
import java.util.stream.IntStream;

@RestController
@RequestMapping("/flux")
public class FluxController {

    @GetMapping("/strArray")
    public Flux<String> strArray(){
        String[] strings = new String[4];
        strings[0] = "ww";
        strings[1] = "ss";
        strings[2] = "jj";
        strings[3] = "mm";
        return Flux.fromArray(strings);
    }

    @GetMapping("/fluxCreate")
    public Flux<String> fluxCreate(){
        return Flux.create((sink) -> {
            List<String> list = List.of("11", "22", "33");
            list.forEach(sink::next);
            sink.next("啊实打实");
            sink.complete();
        });
    }

    @GetMapping("/fluxGenerate")
    public Flux<List<String>> fluxGenerate(){
        return Flux.generate((sink) -> {
            List<String> list = List.of("11", "22", "33");
            sink.next(list);
//            List<String> list2 = List.of("44", "55", "66");   //next超过一个报错
//            sink.next(list2);
            sink.complete();
        });
    }

    @GetMapping("/fluxJust")
    public Flux<String> fluxJust(){
        return Flux.just("che","yin","bo");
    }


    /**
     * 一条一条输出
     * @return
     */
    @GetMapping(value = "/fluxStream",produces = "text/event-stream")
    public Flux<String> fluxStream(){
//        Flux<String> stringFlux = Flux.fromStream(IntStream.range(1,5).mapToObj(i -> {
//            try {
//                TimeUnit.SECONDS.sleep(2);
//            } catch (InterruptedException e) {
//                e.printStackTrace();
//            }
//            return "flux data--" + i;
//        }));
        List<String> strings = new ArrayList<>();
        strings.add("che");
        strings.add("yin");
        strings.add("bo");
        Flux<String> stringFlux = Flux.fromStream(strings.stream()
                .map(o -> {
                    try {
                        TimeUnit.SECONDS.sleep(2);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                    return o;
                }));
        return stringFlux;
    }

}
